package com.once;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.SimpleAdapter;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.once.databinding.ActivityMainBinding;
import com.once.db.DaoSession;
import com.once.db.POJODao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author 张成
 */
public class MainActivity extends AppCompatActivity {
    public static String txt_company;
    public static String txt_category;
    public static String txt_date;
    boolean open = false;

    private ActivityMainBinding binding;
    private DaoSession daoSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initPermit();
        daoSession = ((MyApplication) getApplication()).getDaoSession();

        binding.riqi.setText(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()));
        binding.MainlistView.setOnItemClickListener((adapterView, view, i, l) -> {
            Map<String, String> item = (Map<String, String>) adapterView.getItemAtPosition(i);
            binding.danwei.setText(item.get("company"));
            binding.pinming.setText(item.get("category"));
        });
        binding.MainlistView.setOnItemLongClickListener((adapterView, view, i, l) -> {
            final Map<String, String> item = (Map<String, String>) adapterView.getItemAtPosition(i);
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("重要提示");
            builder.setMessage("是否删除「" + item.get("company") + "&" + item.get("category") + "」的全部数据！");
            builder.setCancelable(true);
            //设置正面按钮
            builder.setPositiveButton("确定", (dialog, which) -> {
                daoSession.queryBuilder(POJO.class)
                        .where(POJODao.Properties.Category.eq(item.get("category")))
                        .where(POJODao.Properties.Company.eq(item.get("company")))
                        .buildDelete()
                        .executeDeleteWithoutDetachingEntities();
                onStart();
            });
            //设置反面按钮
            builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
            builder.show();
            return true;
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        ArrayList<Map<String, String>> arrayList = new ArrayList<>();
        Cursor cursor = daoSession.getDatabase().rawQuery("SELECT DISTINCT COMPANY,CATEGORY FROM POJO", null);
        while (cursor.moveToNext()) {
            Map<String, String> map = new HashMap<>(5);
            map.put("company", cursor.getString(cursor.getColumnIndex("COMPANY")));
            map.put("category", cursor.getString(cursor.getColumnIndex("CATEGORY")));
            arrayList.add(map);
        }
        cursor.close();
        System.out.println(arrayList.size());
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, arrayList, R.layout.list_item, new String[]{"company", "category"}, new int[]{R.id.item_title, R.id.item_text});
        binding.MainlistView.setAdapter(simpleAdapter);
    }


    public void start(View view) {
        if (!open) {
            ToastUtils.show("未授权读写文件权限！无法录入");
            return;
        }

        txt_company = String.valueOf(binding.danwei.getText());
        txt_category = binding.pinming.getText() + "";
        txt_date = binding.riqi.getText() + "";

        if (TextUtils.isEmpty(txt_company) || TextUtils.isEmpty(txt_category) || TextUtils.isEmpty(txt_date)) {
            ToastUtils.show("不可为空");
            return;
        }
        startActivity(new Intent(this, GuigeActivity.class));
    }

    private void initPermit() {

        XXPermissions.with(MainActivity.this)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            open = true;
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.show("被永久拒绝授权，请手动授予存储权限");
                            XXPermissions.startPermissionActivity(MainActivity.this, permissions);
                        } else {
                            ToastUtils.show("获取存储权限失败");
                        }
                    }

                });
    }
}
